<template>
  <div class="c-bg-white c-pt30" v-if="isFrom">
    <my-small-tabbar id="tabhBar" :tabList="tabList" :tabIndex="typeBar" :tabHeight="50" @changeTab="changeType"></my-small-tabbar>
    <div v-if="!isiOS" :class="((typeBar == 1 && vipList.length > 0) || (typeBar == 2 && svipList.length > 0)) ? '' : ''" class="c-pt48 c-pb48 c-w100 c-contexty-hidden c-contextX-scroll c-flex-row c-pl24">
      <div class="c-flex-shrink0 c-pr20" v-for="(item) in (typeBar ==1 ? vipList : svipList)" :key="item.cmpId" @click="chooseVIP(item)">
        <div class="c-ww180 c-br10 c-flex-column c-p c-h" :class="cmpId==item.cmpId ? (typeBar == 1 ? 'vipChooseBG' : 'svipChooseBG') : 'vipNoChooseBG'">
          <div class="c-pa c-p-l0 c-ph12 c-hh32 c-fs20 c-textAlign-c vip-activite-bg" v-if="item.isOnSales" style="left: -2px; top: -0.6rem">{{item.sales.sales.tag && String(item.sales.sales.tag).length < 6 ? item.sales.sales.tag : (Number(item.sales.price) == 0 ? '限时免费' : '限时折扣')}}</div>
          <div class="c-pa c-p-l0 c-ph12 c-hh32 c-fs20 c-textAlign-c vip-activite-bg" v-else-if="dataInfo.isNewUser && item.newUserPrice" style="left: -2px; top: -0.6rem">新用户价</div>
          <div class="c-pa c-p-l0 c-ph12 c-hh32 c-fs20 c-textAlign-c vip-activite-bg" v-else style="left: -2px; top: -0.6rem; opacity: 0;">无</div>
          <div class="c-flex-column c-aligni-center c-pt18 c-pb18">
            <span class="c-fs26 c-fw-b c-fc-sblack" v-if="item.duration < 0">永久</span>
            <span class="c-fs26 c-fw-b c-fc-sblack" v-else>{{item.duration + getDurationUnit(item)}}</span>
            <div class="c-fs0 c-fw-b c-pt12" :class="typeBar == 1 ? 'vip-price-color' : 'svip-price-color'">
              <span class="c-fs24">{{'￥' | iosPriceFilter}}</span>
              <span class="c-fs32">{{parseInt(getShowPrice(item))}}</span> <!--展示的价格优先级:活动价>新人价>购买价-->
              <span class="c-fs24">{{showNumSecondPos(getShowPrice(item))}}</span> <!--展示的价格整数部分和小数部分的字体大小不同-->
            </div>
            <div class="c-flex-column c-aligni-center c-pt12 c-minh48" :class="typeBar == 1 ? 'vip-price-color' : 'svip-price-color'">
              <span class="c-fs20 c-text-decoration-through" v-if="dataInfo.isNewUser && item.newUserPrice || item.isOnSales">{{'原价' + item.price + '元'}}</span><!--前面展示新人价或活动价时划线的是购买价-->
              <span class="c-fs20 c-text-decoration-through" v-else-if="item.marketPrice && Number(item.marketPrice)">{{'原价' + Number(item.marketPrice) + '元'}}</span><!--划线价-->
              <span class="c-fs20" v-else-if="item.duration > 0">{{(item.price/item.duration).toFixed(2) + '元/' + getDurationUnit(item, 2)}}</span><!--折合价-->
              <span class="c-fs20" v-if="item.isRenew == 1 && item.duration > 0">{{'续费'+ Number((item.renewRate*item.price/100).toFixed(2)) + '元'}}</span><!--续费价-->
            </div>
          </div>
        </div>
      </div>
    </div>
    <template v-if="vipGroupPurchase == 2">
      <div class="c-hh10 c-bg-sgray"></div>
      <div class="c-mt10 c-bg-white">
        <div class="c-fs28 c-ph24 c-pt26 c-pb22 c-bd-b1">请选择团购规格</div>
        <div v-for="(item, index) in ladders" :key="index" :class="index == (ladders.length - 1) ? '' : 'c-bd-b1'" class="c-ph24 c-flex-row c-aligni-center c-pv18">
          <div class="c-fs22 c-fc-xblack c-w0 c-flex-grow1">{{item.number}} ：¥{{item.price}}</div>
          <div class="c-flex-row c-aligni-center">
            <shop-number
              :canInputMin='true'
              :min='item.minBuyNumber'
              :max="item.maxBuyNumber"
              :inputNum='item.selectBuyNumber'
              :itemIndex="index"
              @subNum='subNum(arguments, index)'
              @addNum='addNum(arguments, index)'
              @inputChange='inputChange(arguments, index)'
              @finishInput='finishInput(arguments, index)'
            ></shop-number>
            <div class="iconfont c-fs32 c-lh c-ml40" @click="selectLadderItem(index)" :class="index == selectIndex ? 'theme-fc' : 'c-fc-gray'">{{index == selectIndex ? '&#xe6b1;' : '&#xe692;'}}</div>
          </div>
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import MySmallTabbar from "@/components/templates/common/MySmallTabbar.vue";
import ShopNumber from "@/components/templates/shopNumber.vue";
import { utilJs } from "@/utils/common.js";
export default {
  name: 'VipTemplate',
  props: {
    vipGroupPurchase: {
      type: Number,
      default: 1, //2 企业团购
    },
  },
  components: {
    MySmallTabbar,
    ShopNumber
  },
  data() {
    return {
      tabList: [{
        title: 'VIP套餐',
        index: 1,
      }],
      typeBar: 1,
      companyAuth: JSON.parse(localStorage.getItem("companyAuth")),
      isiOS: navigator.userAgent.indexOf('IOSLogin') > -1 || navigator.userAgent.indexOf('IOSNewLogin') > -1 || navigator.userAgent.indexOf("IOSNewApp") > -1,
      vipList: [],
      svipList: [],
      dataInfo: null,
      enableSvipModule: 0,
      isSendVip: 0,
      isVipReNew: 0, //是否属于VIP续费
      isSvipReNew: 0, //是否属于SVIP续费
      enableCouponCount: 0,
      unableCouponCount: 0,
      vipType: 1,
      pId: null, //VIP限时购的extraId
      cmpId: null, //当前选中的VIP种类ID
      presentPrice: 0, //赠送会员价值
      presentLast: 0, //赠送会员时间
      newUserPrice: null,
      isSetRenew: -1,
      isFrom: 0, //是否来自与赠送好友
      ladders: [],
      selectShopNum: 1,
      selectIndex: 0,
      selectGroupId: 0,
      groupPerPrice: 0,
      groupTotalPrice: 0,
      isFromGroupShare: false,
      isFromGroupOrder: false,
      groupOrderQuantity: 0
    }
  },
  watch: {},
  methods: {
    // 获取时长
    getDurationUnit(item, type = 1) { // durationUnit, 1天，2月，3年
      let tmpStr = type == 1 ? '个' : ''
      let unit = item.durationType == 1 ? (tmpStr + '月') : (item.durationUnit == 1 ? '天' : item.durationUnit == 2 ? (tmpStr + '月') : '年')
      return unit
    },
    //数量增加
    addNum(item, sIndex) {
      // this.selectShopNum = item.inputNumber;
      this.ladders[item[0].itemIndex].selectBuyNumber = item[0].inputNumber;
      if (sIndex == this.selectIndex) {
        this.selectShopNum = item[0].inputNumber;
        this.groupTotalPrice = Number(this.groupPerPrice * this.selectShopNum).toFixed(2);
        this.$emit('groupBuyChange', {groupBuyNum: this.selectShopNum, groupBuyId: this.selectGroupId, groupTotalPrice: this.groupTotalPrice});
      }
    },
    //数量减少
    subNum(item, sIndex) {
      // this.selectShopNum = item.inputNumber;
      this.ladders[item[0].itemIndex].selectBuyNumber = item[0].inputNumber;
      if (sIndex == this.selectIndex) {
        this.selectShopNum = item[0].inputNumber;
        this.groupTotalPrice = Number(this.groupPerPrice * this.selectShopNum).toFixed(2);
        this.$emit('groupBuyChange', {groupBuyNum: this.selectShopNum, groupBuyId: this.selectGroupId, groupTotalPrice: this.groupTotalPrice});
      }
    },
    //输入数量
    inputChange(item, sIndex) {
      // this.selectShopNum = item.inputNumber;
      this.ladders[item[0].itemIndex].selectBuyNumber = item[0].inputNumber;
      if (sIndex == this.selectIndex) {
        this.selectShopNum = item[0].inputNumber;
        this.groupTotalPrice = Number(this.groupPerPrice * this.selectShopNum).toFixed(2);
        this.$emit('groupBuyChange', {groupBuyNum: this.selectShopNum, groupBuyId: this.selectGroupId, groupTotalPrice: this.groupTotalPrice});
      }
    },
    finishInput(item, sIndex) {
      // this.selectShopNum = item.inputNumber;
      this.ladders[item[0].itemIndex].selectBuyNumber = item[0].inputNumber;
      if (sIndex == this.selectIndex) {
        this.selectShopNum = item[0].inputNumber;
        this.groupTotalPrice = Number(this.groupPerPrice * this.selectShopNum).toFixed(2);
        this.$emit('groupBuyChange', {groupBuyNum: this.selectShopNum, groupBuyId: this.selectGroupId, groupTotalPrice: this.groupTotalPrice});
      }
    },
    selectLadderItem(sIndex) {
      this.selectIndex = sIndex;
      this.selectShopNum = this.ladders[sIndex].selectBuyNumber;
      this.groupPerPrice = Number(this.ladders[sIndex].price);
      this.groupTotalPrice = Number(this.groupPerPrice * this.selectShopNum).toFixed(2);
      this.$emit('groupBuyChange', {groupBuyNum: this.selectShopNum, groupBuyId: this.selectGroupId, groupTotalPrice: this.groupTotalPrice});
    },
    //得到小数点后两位
    showNumSecondPos(num) {
      num = Number(num);
      let out = Math.floor(num * 100 - parseInt(num) * 100);
      if (out == 0) {
        return '';
      } else if (out < 10) {
        return '.0' + String(out);
      } else if (out % 10 == 0) {
        return '.' + String(out / 10);
      } else {
        return '.' + String(out);
      }
    },
    // 应该展示的总价:活动价>新人价>购买价
    getShowPrice(item) {
      if (item.isOnSales) {
        return item.sales.price;
      } else if (this.dataInfo.isNewUser && item.newUserPrice) {
        return item.newUserPrice;
      } else {
        return item.price;
      }
    },
    // 数据初始化
    getVIPInfo() {
      let $this = this;
      let promise = new Promise((resolve, reject) => {
        utilJs.getMethod(global.apiurl + "members/vipUpPage?type=1", function (res) {
          $this.dataInfo = res;
          $this.vipType = res.userInfo.vipType;
          // $this.enableCouponCount = res.couponList.enable.length;
          // $this.unableCouponCount = res.couponList.unable.length;
          if ($this.vipGroupPurchase == 2) {
            $this.vipList = res.vipList.filter(item => {
              return item.enterpriseGroup;
            });
            if ($this.vipList.length == 0) {
              $this.typeBar = 2;
              $this.tabList = [{
                title: 'SVIP套餐',
                index: 2,
              }];
            }
          } else {
            $this.vipList = res.vipList;
          }
          $this.isVipReNew = res.isRenew;
          $this.isSendVip = $this.isSendVip || res.isSendVip;
          $this.enableSvipModule = res.enableSvipModule;
          if ($this.enableSvipModule && $this.companyAuth.enableSvipSpec) {
            if ($this.vipGroupPurchase != 2 || ($this.vipGroupPurchase == 2 && $this.vipList.length > 0)) {
              $this.tabList = [{
                title: 'VIP套餐',
                index: 1,
              }, {
                title: 'SVIP套餐',
                index: 2,
              }];
            }
            utilJs.getMethod(global.apiurl + "members/vipUpPage?type=2", function (res) {
              $this.dataInfo = res;
              $this.vipType = res.userInfo.vipType;
              // $this.enableCouponCount = res.couponList.enable.length;
              // $this.unableCouponCount = res.couponList.unable.length;
              if ($this.vipGroupPurchase == 2) {
                $this.svipList = res.vipList.filter(item => {
                  return item.enterpriseGroup;
                });
              } else {
                $this.svipList = res.vipList;
              }
              $this.isSvipReNew = res.isRenew;
              $this.isSendVip = $this.isSendVip || res.isSendVip;
              for (let i = 0; i < $this.svipList.length; i++) {
                if ($this.svipList[i].sales && $this.svipList[i].sales.status && ($this.svipList[i].sales.limit == 0 || $this.svipList[i].sales.balance > 0) && $this.companyAuth.enableFlashSalesModule == 1) { //若是限时购，则把价格设置成限时购的价格
                  let nt = (new Date()).getTime();
                  let st = utilJs.getTimeByDate($this.svipList[i].sales.sales.startTime);
                  let et = utilJs.getTimeByDate($this.svipList[i].sales.sales.endTime);
                  if (nt >= st && nt < et && $this.svipList[i].sales.sales.status > -1) {
                    $this.svipList[i].sales.sales.status = 2;
                    $this.svipList[i].isOnSales = true; //可以使用限时购
                    //$this.vipList[i].price = $this.vipList[i].sales.price;
                  } else if (nt < st && $this.vipList[i].sales.sales.status == 1) {
                    $this.svipList[i].sales.sales.status = 1;
                    $this.svipList[i].isOnSales = false;
                  } else if (nt >= et && $this.svipList[i].sales.sales.status == 2) {
                    $this.svipList[i].sales.sales.status = -1;
                    $this.svipList[i].isOnSales = false;
                  } else {
                    $this.svipList[i].isOnSales = false;
                  }
                }
              }
              if ($this.svipList.length == 0) {
                $this.tabList = [{
                  title: 'VIP套餐',
                  index: 1,
                }];
              }
              if ($this.typeBar == 2 && $this.svipList.length > 0) {
                let item = null;
                if (($this.isFromGroupShare || $this.isFromGroupOrder) && $this.$route.query.isFrom == 4 && $this.$route.query.prodId) {
                  let arrTmp = $this.svipList.filter(vItem => {
                    return vItem.cmpId == Number($this.$route.query.prodId)
                  })
                  item = arrTmp && arrTmp.length > 0 ? arrTmp[0] : $this.svipList[0];
                } else {
                  item = $this.svipList[0];
                }
                $this.chooseVIP(item);
              } else if ($this.vipList.length > 0) {
                let item = null;
                if (($this.isFromGroupShare || $this.isFromGroupOrder) && $this.$route.query.isFrom == 4 && $this.$route.query.prodId) {
                  let arrTmp = $this.vipList.filter(vItem => {
                    return vItem.cmpId == Number($this.$route.query.prodId)
                  })
                  item = arrTmp && arrTmp.length > 0 ? arrTmp[0] : $this.vipList[0];
                } else {
                  item = $this.vipList[0];
                }
                $this.chooseVIP(item);
              }
              if ($this.vipGroupPurchase == 2 && $this.vipList.length == 0 && $this.svipList.length == 0) {
                $this.$routerGo($this, "replace", {
                  path: "/error/emptyPage",
                  query: {
                    from: "",
                    info: "未找到企业拼团活动"
                  }
                });
              }
              resolve();
            });
          } else {
            $this.tabList = [{
              title: 'VIP套餐',
              index: 1,
            }];
            resolve();
          }
          for (let i = 0; i < $this.vipList.length; i++) {
            if ($this.vipList[i].sales && $this.vipList[i].sales.status && ($this.vipList[i].sales.limit == 0 || $this.vipList[i].sales.balance > 0) && $this.companyAuth.enableFlashSalesModule == 1) { //若是限时购，则把价格设置成限时购的价格
              let nt = (new Date()).getTime();
              let st = utilJs.getTimeByDate($this.vipList[i].sales.sales.startTime);
              let et = utilJs.getTimeByDate($this.vipList[i].sales.sales.endTime);
              if (nt >= st && nt < et && $this.vipList[i].sales.sales.status > -1) {
                $this.vipList[i].sales.sales.status = 2;
                $this.vipList[i].isOnSales = true; //可以使用限时购
                //$this.vipList[i].price = $this.vipList[i].sales.price;
              } else if (nt < st && $this.vipList[i].sales.sales.status == 1) {
                $this.vipList[i].sales.sales.status = 1;
                $this.vipList[i].isOnSales = false;
              } else if (nt >= et && $this.vipList[i].sales.sales.status == 2) {
                $this.vipList[i].sales.sales.status = -1;
                $this.vipList[i].isOnSales = false;
              } else {
                $this.vipList[i].isOnSales = false;
              }
            }
          }
          if ($this.typeBar == 2 && $this.svipList.length > 0) {
            // let item = $this.svipList[0];
            // $this.chooseVIP(item);
            let item = null;
            if (($this.isFromGroupShare || $this.isFromGroupOrder) && $this.$route.query.isFrom == 4 && $this.$route.query.prodId) {
              let arrTmp = $this.svipList.filter(vItem => {
                return vItem.cmpId == Number($this.$route.query.prodId)
              })
              item = arrTmp && arrTmp.length > 0 ? arrTmp[0] : $this.svipList[0];
            } else {
              item = $this.svipList[0];
            }
            $this.chooseVIP(item);
          } else if ($this.vipList.length > 0) {
            let item = null;
            if (($this.isFromGroupShare || $this.isFromGroupOrder) && $this.$route.query.isFrom == 4 && $this.$route.query.prodId) {
              let arrTmp = $this.vipList.filter(vItem => {
                return vItem.cmpId == Number($this.$route.query.prodId)
              })
              item = arrTmp && arrTmp.length > 0 ? arrTmp[0] : $this.vipList[0];
            } else {
              item = $this.vipList[0];
            }
            $this.chooseVIP(item);
          }
          if (!$this.enableSvipModule && $this.vipGroupPurchase == 2 && $this.vipList.length == 0) {
            $this.$routerGo($this, "replace", {
              path: "/error/emptyPage",
              query: {
                from: "",
                info: "未找到企业拼团活动"
              }
            });
          }
        });
      });
      promise.then(() => {})
    },
    //改变typeBar
    changeType(type) {
      if (this.typeBar != type) {
        this.typeBar = type;
        if (type == 1) {
          this.vipList.length > 0 ? this.chooseVIP(this.vipList[0]) : this.chooseVIP();
        } else {
          this.svipList.length > 0 ? this.chooseVIP(this.svipList[0]) : this.chooseVIP();
        }
      }
      return false;
    },
    //选择要购买的VIP种类
    chooseVIP(item) {
      this.cmpId = item.cmpId;
      this.isSetRenew = item.isSetRenew;
      this.newUserPrice = item.newUserPrice;
      this.presentPrice = item.price;
      if (item.duration == -1) {
        this.presentLast = '永久' + (this.typeBar == 1 ? 'VIP' : 'SVIP');
      } else {
        this.presentLast = item.duration + this.getDurationUnit(item) + (this.typeBar == 1 ? 'VIP' : 'SVIP');
      }
      this.pId = item.isOnSales ? item.sales.pId : null; //限时购
      //这个根据具体需求定
      //目前是赠送会员引用次组件
      let ptFrom = "";
      if (this.pId) { //限时购
        ptFrom = this.typeBar == 1 ? global.ckFrom.flashSalesPresentVip : global.ckFrom.flashSalesPresentSvip;
      } else { //非限时购
        ptFrom = this.typeBar == 1 ? global.ckFrom.presentVip : global.ckFrom.presentSvip;
      }
      let ckFrom = null;
      if (ptFrom == global.ckFrom.presentVip || ptFrom == global.ckFrom.presentSvip) {
        ckFrom = global.ckFrom.vip; //赠送会员在提交订单时区分
      } else if (ptFrom == global.ckFrom.flashSalesPresentVip) {
        ckFrom = global.ckFrom.flashSalesPresentVip;
      } else if (ptFrom == global.ckFrom.flashSalesPresentSvip) {
        ckFrom = global.ckFrom.flashSalesPresentSvip;
      }
      if (this.vipGroupPurchase == 2) {
        let orderSelectedIndex = 0;
        ptFrom = this.typeBar == 1 ? global.ckFrom.vip : global.ckFrom.svip;
        this.ladders = item.enterpriseGroup ? item.enterpriseGroup.ladder : [];
        for (let i = 0; i < this.ladders.length; i++) {
          if (this.isFromGroupOrder && (item.cmpId == Number(this.$route.query.prodId)) && (this.groupOrderQuantity >= this.ladders[i].minBuyNumber) && (this.ladders[i].maxBuyNumber > this.groupOrderQuantity)) {
            this.$set(this.ladders[i], "selectBuyNumber", this.groupOrderQuantity);
            orderSelectedIndex = i;
          } else {
            this.$set(this.ladders[i], "selectBuyNumber", this.ladders[i].minBuyNumber);
          }
        }
        this.selectGroupId = item.enterpriseGroup ? item.enterpriseGroup.id : 0;
        this.selectLadderItem(orderSelectedIndex);
      }
      let vipInfo = {
        "vId": this.cmpId,
        "pId": this.pId,
        "ptFrom": ptFrom,
        "vipType": this.typeBar == 1 ? 2 : 4,
        "ckFrom": ckFrom
      }
      this.$emit('chooseVip', vipInfo);
    },
  },
  activated() {
    this.isFrom = this.$route.query.isFrom || 0;
    this.isFromGroupShare = this.$route.query.isFromShare ? true : false; //企业拼团后台管理分享链接进来
    this.isFromGroupOrder = this.$route.query.isFromGroupOrder ? true : false; //企业拼团我的待付款订单跳转过来
    if (this.isFromGroupOrder && this.$route.query.quantity) {
      this.groupOrderQuantity = Number(this.$route.query.quantity) //从企业拼团我的待付款订单跳转过来，默认选择待付款的购买数量
    }
    // isFrom 为 3 是来自升级服务上必须购买指定会员，所以不需要会员选择
    if ((this.$route.query.isFrom && this.$route.query.isFrom != 3 && !this.$route.query.orderId) || this.$route.query.isFrom == 4) {
      this.typeBar = Number(this.$route.query.isFrom) == 4 && (this.isFromGroupShare || this.isFromGroupOrder) && Number(this.$route.query.type) == 23 ? 2 : 1;
      this.getVIPInfo();
    }
  },
  deactivated() {
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.priceColor {
  color: #DAAC6A;
}
.vipNoChooseBG {
  border: 2px solid #e8e8e8;
}
.vipChooseBG {
  background: #fff7e6;
  border: 2px solid #dcb66c;
  box-shadow: 0px 10px 20px 0px rgba(226,176,121,0.20);
}
.svipChooseBG {
  background: #fff6ef;
  border: 2px solid #dba988;
  box-shadow: 0px 10px 20px 0px rgba(219,169,136,0.20);
}
.vip-activite-bg {
  color: #eadbac;
  background: linear-gradient(#252531 0%, #4e4e5c 0%, #23232f 100%);
  border-radius: 8px 2px 8px 2px;
}
.vip-price-color {
  color: #AA7525;
}
.svip-price-color {
  color: #895B42;
}
.c-minh48 {
  min-height: 1.2rem;
}
</style>
